//
//  SWStatusViewModel.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/3/3.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit
import SDWebImage

class SWStatusViewModel: NSObject {
    
    
    private var loadingStatus = false
    /**
     获取微博先去数据库找 没有再请求数据
     
     - parameter loadStatusCallBack: 完成回调 [SWStatus]
     */
    func loadStatus(since_id: Int,  max_id: Int , loadStatusCallBack:(statuses: [SWStatus]? , error: NSError?) ->() ) {
        
        //正在加载微博 避免复请求数据
        if loadingStatus {
            let error = SWNetWorkToolError.statusLoading.error()
            loadStatusCallBack(statuses: nil, error: error)
        }
        //还没加载数据 到这里开始加载
        loadingStatus = true
        
        SWStatusDAL.sheadDAL.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            //已经加载完数据
            self.loadingStatus = false
            if error != nil {
                loadStatusCallBack(statuses: nil, error: error)
                return
            }
           
            //空模型数组
            var status = [SWStatus]()
            
            for dict in statuses! {
                //字典转模型
                let statu = SWStatus(dict: dict)
            
                status.append(statu)
            }
            //回调控制器之前下载图片
            self.loadWebImage(status, loadStatusCallBack: loadStatusCallBack)
        }
        
        
        
        //调用网络工具类
//        SWNetWorkTool.sharedNetWorkTool.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
//            if  error != nil {
//                //获取微博数据失败 告诉控制器
//                loadStatusCallBack(statuses: nil, error: error)
//                return
//            }
//            //从result字典中获取statuses数组 statuses里面存有字典
//            if let array = result?["statuses"] as? [[String : AnyObject]] {
//                
//                var statuses = [SWStatus]()
//                
//                for dict in array {
//                    //字典转模型
//                    let status = SWStatus(dict: dict)
//                    
//                    statuses.append(status)
//                }
//                //通知控制器之前下载图片 再告诉控制器显示
//                self.loadWebImage(statuses, loadStatusCallBack: loadStatusCallBack)
//                //完成回调
////                loadStatusCallBack(statuses: statuses, error: nil)
//            } else{
//                //什么都获取不了
//                loadStatusCallBack(statuses: nil, error: nil)
//            }
//        }
    }
    
    /**
     预先下载图片
     
     - parameter statues: 微博模型数组
     */
    func loadWebImage(statues: [SWStatus] ,loadStatusCallBack:(statuses: [SWStatus]? , error: NSError?) ->() ) {
    print("bundle: \(NSHomeDirectory())")
        let group = dispatch_group_create()
        
        var lenght = 0
        
        
        for status in statues {
            var urls = [NSURL]()
        
            //原创微博的配图的rul数组
            if let downloadURL = status.storePictureURLs {
                urls = downloadURL
            
            }
            //转发
            if let downloadURL = status.retweeted_status?.storePictureURLs {
            
                urls = downloadURL
            }
            
            //图片数组 拿出第一张
            if urls.count == 1{
                let url = urls.first
                //进入组
                dispatch_group_enter(group)
                //下载图片
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    //离开组
                    dispatch_group_leave(group)
                    if error != nil {
                        print("下载出错 \(error)")
                        return
                    }
                    
                    let data = UIImagePNGRepresentation(image)
                    lenght += data!.length
                })
            }
        }
        //for in完后所有图片下载完成会触发
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
//            print("\(group)")
//            print("所以图片下载完成，通知控制器：缓存图片大小：\(CGFloat(lenght) / 1024.0 / 1024.0)MB")
            loadStatusCallBack(statuses: statues, error: nil)
//            print("\(NSThread.currentThread())")
        }
    }
}
